package com.atguigu.cloud.controller;

import com.atguigu.cloud.entities.PayDTO;
import com.atguigu.cloud.resp.ResultData;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * 订单控制器
 *
 * @author Kotori rotroutine@163.com
 * @since 2025/2/28
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/consumer")
public class OrderController {
    private static final String PAYMENT_SERVICE_URL = "http://cloud-payment-service";

    private final RestTemplate restTemplate;

    @GetMapping("/pay/add")
    public ResultData<?> addOrder(@RequestBody PayDTO payDTO) {
        return restTemplate.postForObject(PAYMENT_SERVICE_URL + "/pay/add", payDTO, ResultData.class);
    }

    @GetMapping("/pay/get/{id}")
    public ResultData<?> getPayInfo(@PathVariable("id") Integer id) {
        return restTemplate.getForObject(PAYMENT_SERVICE_URL + "/pay/get/" + id, ResultData.class, id);
    }

    @GetMapping("/pay/getAll")
    public ResultData<?> getAllPayInfo() {
        return restTemplate.getForObject(PAYMENT_SERVICE_URL + "/pay/getAll", ResultData.class);
    }

    @GetMapping("/pay/update")
    public ResultData<?> updateOrder(@RequestBody PayDTO payDTO) {
        restTemplate.put(PAYMENT_SERVICE_URL + "/pay/update", payDTO);
        return ResultData.success();
    }

    @GetMapping("/pay/delete/{id}")
    public ResultData<?> deleteOrder(@PathVariable("id") Integer id) {
        restTemplate.delete(PAYMENT_SERVICE_URL + "/pay/delete/" + id);
        return ResultData.success();
    }

    // @GetMapping(value = "/consumer/pay/get/info")
    // private ResultData<?> getInfoByConsul() {
    //     return restTemplate.getForObject(PAYMENT_SERVICE_URL + "/pay/get/info", ResultData.class);
    // }

    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping(value = "/pay/get/info")
    private String getInfoByConsul() {
        return restTemplate.getForObject(PAYMENT_SERVICE_URL + "/pay/get/info", String.class);
    }

    @GetMapping("/discovery")
    public String discovery() {
        List<String> services = discoveryClient.getServices();
        for (String element : services) {
            System.out.println(element);
        }

        System.out.println("===================================");

        List<ServiceInstance> instances = discoveryClient.getInstances("cloud-payment-service");
        for (ServiceInstance element : instances) {
            System.out.println(element.getServiceId() + "\t" + element.getHost() + "\t" + element.getPort() + "\t" + element.getUri());
        }

        return instances.getFirst().getServiceId() + ":" + instances.getFirst().getPort();
    }
}
